package com.deng.controller;


import cn.hutool.core.map.MapUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.deng.common.lang.Result;
import com.deng.config.RabbitConfig;
import com.deng.entity.*;
import com.deng.search.mq.PostMqIndexMessage;
import com.deng.util.ValidationUtil;
import com.deng.vo.CommentVo;
import com.deng.vo.PostVo;
import org.springframework.stereotype.Controller;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.bind.annotation.*;

import com.deng.controller.BaseController;

import java.util.Date;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author dengwenxiong
 * @since 2021-05-05
 */
@Controller
public class PostController extends BaseController {
    @RequestMapping("/category/{id}")//":\\d"指定id为0-9
    public String category(@PathVariable(name="id")Long id){
        int pn=ServletRequestUtils.getIntParameter(req,"pn",1);
        req.setAttribute("currentCategoryId", id);//点击当前分类后分类颜色变化
        req.setAttribute("pn",pn);

        return "post/category";
    }
    //博客详情页。每访问一次浏览量就加一
    @GetMapping("/post/{id:\\d*}")//":\\d"指定id的参数类型
    public String detail(@PathVariable(name="id")Long id){
        PostVo vo=postService.selectOnePost(new QueryWrapper<Post>().eq("p.id",id));
        Assert.notNull(vo,"文章以被删除");
        //浏览量
        postService.putViewCount(vo);
        //参数：分页，文章id，用户，排序
        IPage<CommentVo> results=commentService.paging(getPage(),vo.getId(),null,"created");
        req.setAttribute("currentCategoryId", vo.getId());
        req.setAttribute("post",vo);
        req.setAttribute("pageData",results);
        return "post/detail";
    }
    //判断用户是否收藏文章
    @PostMapping("/collection/find")
    @ResponseBody
    public Result collection(Long pid){
       int count= usercollectionService.count(new QueryWrapper<Usercollection>().eq("user_id",getProfileId()).eq("post_id",pid));
        return Result.success(MapUtil.of("collection",count>0));
    }
    //将文章添加到收藏
    @PostMapping("/collection/add")
    @ResponseBody
    public Result addCollection(Long pid){
        Post post=postService.getById(pid);
        Assert.isTrue(post!=null,"文章已被删除");
        int count= usercollectionService.count(new QueryWrapper<Usercollection>().eq("user_id",getProfileId()).eq("post_id",pid));
        if(count>0) return Result.fail("已经收藏了该文章");
        Usercollection usercollection=new Usercollection();
        usercollection.setUserId(getProfileId());
        usercollection.setPostId(pid);
        usercollection.setCreated(new Date());
        usercollection.setModified(new Date());
        usercollection.setPostUserId(post.getUserId());
        usercollectionService.save(usercollection);
        return Result.success();
    }
    //移除收藏
    @PostMapping("/collection/remove")
    @ResponseBody
    public Result removeCollection(Long pid){
        Post post=postService.getById(pid);
        Assert.isTrue(post!=null,"文章已被删除");
        usercollectionService.remove(new QueryWrapper<Usercollection>().eq("user_id",getProfileId()).eq("post_id",pid));
        return Result.success();
    }
    //编辑或添加文章
    @GetMapping("/post/edit")
    public String edit(){
        //根据请求参数是否有id来判断是添加还是编辑文章
        String id=req.getParameter("id");
        if(!StringUtils.isEmpty(id)){
            Post post=postService.getById(id);
            Assert.isTrue(post!=null,"文章已被删除");
            Assert.isTrue(post.getUserId()==getProfileId().longValue(),"没有权限操作");
            req.setAttribute("post",post);
        }
        req.setAttribute("categories",categoryService.list());
        return "/post/edit";
    }
    //发布文章
    @PostMapping("/post/submit")
    @ResponseBody
    public Result submit(Post post){
        //验证post内容不能为空
        ValidationUtil.ValidResult validResult = ValidationUtil.validateBean(post);
        if(validResult.hasErrors()) {
            return Result.fail(validResult.getErrors());
        }
        //添加文章没有id，编辑文章有id
        if(post.getId() == null) {
            post.setUserId(getProfileId());
            post.setModified(new Date());
            post.setCreated(new Date());
            post.setCommentCount(0);
            post.setEditMode(null);
            post.setLevel(0);
            post.setRecommend(false);
            post.setViewCount(0);
            post.setVoteDown(0);
            post.setVoteUp(0);
            postService.save(post);
        } else {
            Post tempPost = postService.getById(post.getId());
            Assert.isTrue(tempPost.getUserId().longValue() == getProfileId().longValue(), "无权限编辑此文章！");
            tempPost.setTitle(post.getTitle());
            tempPost.setContent(post.getContent());
            tempPost.setCategoryId(post.getCategoryId());
            postService.updateById(tempPost);
        }
        //通知消息给mq，告知更新或者添加
        amqpTemplate.convertAndSend(RabbitConfig.ES_EXCHANGE,RabbitConfig.ES_BIND_KEY,new PostMqIndexMessage(post.getId(),PostMqIndexMessage.CREATE_OR_UPDATE));
        return Result.success().action("/post/"+post.getId());
    }
    @ResponseBody
    @PostMapping("/post/delete")
    public Result delete(Long id) {
        Post post = postService.getById(id);

        Assert.notNull(post, "该帖子已被删除");
        Assert.isTrue(post.getUserId().longValue() == getProfileId().longValue(), "无权限删除此文章！");

        postService.removeById(id);

        // 删除相关消息、收藏等
        usermessageService.removeByMap(MapUtil.of("post_id", id));
        usercollectionService.removeByMap(MapUtil.of("post_id", id));
        //通知消息给mq，告知更新或者添加
        amqpTemplate.convertAndSend(RabbitConfig.ES_EXCHANGE,RabbitConfig.ES_BIND_KEY,new PostMqIndexMessage(post.getId(),PostMqIndexMessage.CREATE_OR_UPDATE));
        return Result.success().action("/");
    }
    //评论与回复
    @ResponseBody
    @PostMapping("/post/reply")
    public Result reply(Long jid,String content){
        Assert.notNull(jid,"找不到对应文章");
        Assert.hasLength(content,"评论内容不能为空");
        Post post = postService.getById(jid);
        Assert.isTrue(post != null, "该文章已被删除");

        Comment comment = new Comment();
        comment.setPostId(jid);
        comment.setContent(content);
        comment.setUserId(getProfileId());
        comment.setCreated(new Date());
        comment.setModified(new Date());
        comment.setLevel(0);
        comment.setVoteDown(0);
        comment.setVoteUp(0);
        commentService.save(comment);
        //文章评论数加一
        post.setCommentCount(post.getCommentCount()+1);
        postService.updateById(post);
        //本周热议对应的文章评论自动加一
        postService.incrCommentCountAndUnionForWeekRank(post.getId(),true);
        //通知作者有人评论了文章，如果当前评论者就是文章作者则不用通知
        if(comment.getUserId()!=post.getUserId()) {
            Usermessage usermessage = new Usermessage();
            usermessage.setPostId(jid);
            usermessage.setCommentId(comment.getId());
            usermessage.setFromUserId(getProfileId());
            usermessage.setToUserId(post.getUserId());
            //评论的类型
            usermessage.setType(1);
            usermessage.setContent(content);
            usermessage.setCreated(new Date());
            usermessage.setStatus(0);
            usermessageService.save(usermessage);
            //即时通知websocket
            webSocketService.senMessCountToUser(usermessage.getToUserId());
        }
        //通知被@的用户有人回复
        if(content.startsWith("@")){
            //截取被@的用户名
            String username=content.substring(1,content.indexOf(" "));
            System.out.println(username);
            User user=userService.getOne(new QueryWrapper<User>().eq("username",username));
            if(user!=null){
                Usermessage usermessage = new Usermessage();
                usermessage.setPostId(jid);
                usermessage.setCommentId(comment.getId());
                usermessage.setFromUserId(getProfileId());
                usermessage.setToUserId(user.getId());
                usermessage.setType(2);
                usermessage.setContent(content);
                usermessage.setCreated(new Date());
                usermessage.setStatus(0);
                usermessageService.save(usermessage);
                //即时通知websocket
                webSocketService.senMessCountToUser(usermessage.getToUserId());
            }
        }
        return Result.success().action("/post/"+post.getId());
    }
    //删除评论
    @ResponseBody
    @PostMapping("/post/jieda-delete")
    public Result deleteComment(Long id){
        Assert.notNull(id, "评论id不能为空！");
        Comment comment = commentService.getById(id);
        Assert.notNull(comment, "找不到对应评论！");
        if(comment.getUserId().longValue() != getProfileId().longValue()) {
            return Result.fail("不是你发表的评论！");
        }
        commentService.removeById(id);
        //文章评论数减少1
        Post post=postService.getById(comment.getPostId());
        post.setCommentCount(post.getCommentCount()-1);
        postService.updateById(post);
        postService.incrCommentCountAndUnionForWeekRank(post.getId(),false);
        return Result.success();

    }
}
